package com.example.administrator.energyida.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.administrator.energyida.activity.FactoryListActivity;
import com.example.administrator.energyida.activity.HomeMapActivity;
import com.example.administrator.energyida.R;
import com.example.administrator.energyida.adapter.ItemGirdviewHomeAdapter;
import com.example.administrator.energyida.beans.EnergyBean;
import com.example.administrator.energyida.beans.RoseBean;
import com.jaeger.library.StatusBarUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.openxu.cview.chart.barchart.BarVerticalChart;
import com.openxu.cview.chart.bean.BarBean;
import com.openxu.cview.chart.rosechart.NightingaleRoseChart;
import com.openxu.utils.DensityUtil;
import com.sunfusheng.marqueeview.MarqueeView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class HomeFragment extends Fragment implements View.OnClickListener {

    private MarqueeView marqueeView;
    private GridView home_gridView;
    private NightingaleRoseChart home_NightingaleRoseChart;
    private BarVerticalChart home_BarVerticalChart;
    private TextView home_text_time;
    private TextView home_text_day;
    private TextView home_text_month;
    private LinearLayout home_liner;
    private TextView home_text_map;
    private TextView home_text_addData;

    private ItemGirdviewHomeAdapter girdviewAdapter;

    private List<Object> roseList = new ArrayList();
    private List<EnergyBean> energyBeans = new ArrayList<>();

    private Boolean flag = true;   // true为“日报”，false为“月报”

    private final Calendar calendar = Calendar.getInstance();
    private int yy = calendar.get(Calendar.YEAR);
    private int mm = calendar.get(Calendar.MONTH) + 1;
    private int dd = calendar.get(Calendar.DAY_OF_MONTH);

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        initView(view);
        
        //点击悬浮按钮，放在onClick里没反应
        home_text_addData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), FactoryListActivity.class);
                startActivity(intent);
            }
        });

        return view;
    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initView(View view) {
        marqueeView = view.findViewById(R.id.marqueeView);
        home_gridView = view.findViewById(R.id.home_gridView);
        home_NightingaleRoseChart = view.findViewById(R.id.home_NightingaleRoseChart);
        home_BarVerticalChart = view.findViewById(R.id.home_BarVerticalChart);
        home_text_time = view.findViewById(R.id.home_text_time);
        home_text_day = view.findViewById(R.id.home_text_day);
        home_text_month = view.findViewById(R.id.home_text_month);
        home_liner = view.findViewById(R.id.home_liner);
        home_text_map = view.findViewById(R.id.home_text_map);
        home_text_addData = view.findViewById(R.id.home_text_addData);

        home_text_time.setOnClickListener(this);
        home_text_day.setOnClickListener(this);
        home_text_month.setOnClickListener(this);
        home_liner.setOnClickListener(this);
        home_text_map.setOnClickListener(this);

        Drawable next = ContextCompat.getDrawable(getContext(), R.drawable.next);
        next.setBounds(0, 0, next.getMinimumWidth(), next.getMinimumHeight());
        home_text_map.setCompoundDrawables(null, null, next, null);
        home_text_map.setPadding(0, 0, 30, 0);

        // 设置状态栏的颜色
        StatusBarUtil.setColor(getActivity(), Color.parseColor("#10cafd"), 50);

        setTextTimeMMPatter(flag);

        // 设置跑马灯效果
        setMarqueeView();

        setGridView(flag);

        initNightingaleRoseChart(flag, home_NightingaleRoseChart);

        initBarVerticalChart(flag, home_BarVerticalChart);

    }

    /**
     * 设置跑马灯效果
     */
    private void setMarqueeView() {
        List<String> messages = new ArrayList<>();
        messages.add("1. 轻轻的我走了，");
        messages.add("2. 正如我轻轻的来；");
        messages.add("3. 我轻轻的招手，");
        messages.add("4. 作别西天的云彩。");
        messages.add("6. 那河畔的金柳，");
        messages.add("7. 是夕阳中的新娘；");
        messages.add("8. 波光里的艳影，");
        messages.add("9. 在我的心头荡漾。");
        marqueeView.startWithList(messages);
    }

    /**
     * 设置GridView
     */
    private void setGridView(boolean b) {
        Drawable addr1 = ContextCompat.getDrawable(getContext(), R.drawable.electricity);
        Drawable addr2 = ContextCompat.getDrawable(getContext(), R.drawable.water);
        Drawable addr3 = ContextCompat.getDrawable(getContext(), R.drawable.gas);
        Drawable addr4 = ContextCompat.getDrawable(getContext(), R.drawable.heat);

        Drawable addrUp = ContextCompat.getDrawable(getContext(), R.drawable.up);
        Drawable addrDwon = ContextCompat.getDrawable(getContext(), R.drawable.down);

        addrUp.setBounds(0, 0, addrUp.getMinimumWidth(), addrUp.getMinimumHeight());
        addrDwon.setBounds(0, 0, addrDwon.getMinimumWidth(), addrDwon.getMinimumHeight());
        energyBeans.clear();
        if (b) {
            energyBeans.add(new EnergyBean(addr1, "本日用电", "53.25 kWh", "同期:9.6%", "上月:39.45 kWh"));
            energyBeans.add(new EnergyBean(addr2, "本日用水", "41.27 T", "同期:1.6%", "上月:56.64 T"));
            energyBeans.add(new EnergyBean(addr3, "本日用气", "54.52 m³", "同期:0.6%", "上月:52.64 m³"));
            energyBeans.add(new EnergyBean(addr4, "本日用热", "90.26 GJ", "同期:2.6%", "上月:96.54 GJ"));
        } else {
            energyBeans.add(new EnergyBean(addr1, "本月用电", "5853.25 kWh", "同期:9.6%", "上月:5319.45 kWh"));
            energyBeans.add(new EnergyBean(addr2, "本月用水", "941.27 T", "同期:1.6%", "上月:956.64 T"));
            energyBeans.add(new EnergyBean(addr3, "本月用气", "354.52 m³", "同期:0.6%", "上月:352.64 m³"));
            energyBeans.add(new EnergyBean(addr4, "本月用热", "510.26 GJ", "同期:2.6%", "上月:496.54 GJ"));
        }
        girdviewAdapter = new ItemGirdviewHomeAdapter(getContext(), energyBeans, new ItemGirdviewHomeAdapter.SetUpOrDownCallback() {
            @Override
            public void callback(boolean b,TextView textView) {
                if (b) {
                    textView.setCompoundDrawables(null,null,addrUp,null);
                } else {
                    textView.setCompoundDrawables(null, null, addrDwon, null);
                }
            }
        });
        home_gridView.setAdapter(girdviewAdapter);
    }

    /**
     * 初始化BarVerticalChart
     *
     * @param chart1
     */
    private void initBarVerticalChart(boolean b, BarVerticalChart chart1) {
        chart1.setBarSpace(DensityUtil.dip2px(getContext(), 1));  //双柱间距
        chart1.setBarItemSpace(DensityUtil.dip2px(getContext(), 20));  //柱间距
        chart1.setYMARK_NUM(10);
        chart1.setDebug(false);
        chart1.setBarNum(4);   //一组柱子数量
        chart1.setBarColor(new int[]{Color.parseColor("#5F93E7"), Color.parseColor("#F28D02"), Color.parseColor("#D4FF33"),Color.parseColor("#FFAB97D5")});
        //X轴
        List<String> strXList = new ArrayList<>();
        //柱状图数据
        List<List<BarBean>> dataList = new ArrayList<>();
        if (b) {
            for (int i = 0; i < 24; i++) {
                //此集合为柱状图上一条数据，集合中包含几个实体就是几个柱子
                List<BarBean> list = new ArrayList<>();
                Random random = new Random();
                list.add(new BarBean(random.nextInt(35), "水"));
                list.add(new BarBean(random.nextInt(30), "电"));
                list.add(new BarBean(random.nextInt(40), "气"));
                list.add(new BarBean(random.nextInt(45), "热"));
                dataList.add(list);
                strXList.add((i + 1) + "小时");
            }
        } else {
            for (int i = 0; i < 30; i++) {
                //此集合为柱状图上一条数据，集合中包含几个实体就是几个柱子
                List<BarBean> list = new ArrayList<>();
                Random random = new Random();
                list.add(new BarBean(random.nextInt(30), "水"));
                list.add(new BarBean(random.nextInt(20), "电"));
                list.add(new BarBean(random.nextInt(50), "气"));
                list.add(new BarBean(random.nextInt(40), "热"));
                dataList.add(list);
                strXList.add((i + 1) + "月");
            }
        }
        chart1.setLableTopSpace(10);
        chart1.setLoading(false);
        chart1.setData(dataList, strXList);
    }

    /**
     * 初始化NightingaleRoseChart
     *
     * @param nightingaleRoseChart
     */
    private void initNightingaleRoseChart(boolean b, NightingaleRoseChart nightingaleRoseChart) {
        nightingaleRoseChart.setShowChartLable(true);    //是否在图表上显示指示lable
        nightingaleRoseChart.setShowChartNum(false);     //是否在图表上显示指示num
        nightingaleRoseChart.setShowNumTouched(false);   //点击显示数量
        nightingaleRoseChart.setShowRightNum(true);      //右侧显示数量
        Random random = new Random();
        roseList.clear();
        if (b) {
            roseList.add(new RoseBean(random.nextInt(30), "用水"));
            roseList.add(new RoseBean(random.nextInt(60), "用电"));
            roseList.add(new RoseBean(random.nextInt(70), "用气"));
            roseList.add(new RoseBean(random.nextInt(50), "用热"));
        } else {
            roseList.add(new RoseBean(random.nextInt(400), "用水"));
            roseList.add(new RoseBean(random.nextInt(500), "用电"));
            roseList.add(new RoseBean(random.nextInt(800), "用气"));
            roseList.add(new RoseBean(random.nextInt(500), "用热"));
        }
        //参数1：数据对象class， 参数2：数量属性字段名称， 参数3：名称属性字段名称， 参数4：数据集合
        nightingaleRoseChart.setData(RoseBean.class, "count", "ClassName", roseList);
        nightingaleRoseChart.setShowNumTouched(true);
        nightingaleRoseChart.setLoading(false);//是否正在加载，数据加载完毕后置为false
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.home_text_map:
                Intent intent = new Intent(getActivity(), HomeMapActivity.class);
                startActivity(intent);
                break;
            case R.id.home_text_time:
                if (flag) {
                    setTimePickerDialog(Type.YEAR_MONTH_DAY, "YY-MM-dd", "请选择日期", "YEAR_MONTH_DAY");
                } else {
                    setTimePickerDialog(Type.YEAR_MONTH, "YY-MM", "请选择月份", "YEAR_MONTH");
                }
                break;
            case R.id.home_text_day:
                flag = true;
                setTextDayOrMonthStyle("#ffffff", "#ff9d9d9e", R.drawable.text_left_bg, R.drawable.text_right_white_bg);
                setTextTimeMMPatter(flag);
                setGridView(flag);
                initNightingaleRoseChart(flag, home_NightingaleRoseChart);
                initBarVerticalChart(flag, home_BarVerticalChart);
                break;
            case R.id.home_text_month:
                flag = false;
                setTextDayOrMonthStyle("#ff9d9d9e", "#ffffff", R.drawable.text_left_white_bg, R.drawable.text_right_bg);
                setTextTimeMMPatter(flag);
                setGridView(flag);
                initNightingaleRoseChart(flag, home_NightingaleRoseChart);
                initBarVerticalChart(flag, home_BarVerticalChart);
                break;
            default:
                break;
        }
    }

    /**
     * 设置TimePickerDialog
     *
     * @param type   TimePickerDialog类型
     * @param patter 格式化时间的样式
     * @param title  TimePickerDialog的标题
     * @param tag    show方法的标签
     */
    private void setTimePickerDialog(Type type, String patter, String title, String tag) {
        new TimePickerDialog.Builder()
                .setType(type)
                .setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        Date date = new Date(millseconds);
                        SimpleDateFormat format = new SimpleDateFormat(patter);
                        String time = format.format(date);
                        home_text_time.setText(time);
                        setGridView(flag);
                        initNightingaleRoseChart(flag, home_NightingaleRoseChart);
                        initBarVerticalChart(flag, home_BarVerticalChart);
                    }
                })
                .setTitleStringId(title)
                .setWheelItemTextSelectorColor(Color.parseColor("#10cafd"))
                .setThemeColor(Color.parseColor("#10cafd"))
                .build()
                .show(getActivity().getSupportFragmentManager(), tag);
    }

    /**
     * 设置在‘日报’和‘月报’两个extView切换时的样式
     *
     * @param dayTextColor  home_text_day的字体颜色
     * @param monthTextColor   home_text_month的字体颜色
     * @param DayBg  home_text_day的背景颜色
     * @param MonthBg  home_text_month的背景颜色
     */
    private void setTextDayOrMonthStyle(String dayTextColor, String monthTextColor, int DayBg, int MonthBg) {
        home_text_day.setTextColor(Color.parseColor(dayTextColor));
        home_text_month.setTextColor(Color.parseColor(monthTextColor));
        home_text_day.setBackgroundResource(DayBg);
        home_text_month.setBackgroundResource(MonthBg);
    }

    /**
     * 设置home_text_time在展示是月还是日时中的MM样式
     *
     * @param flag  true为“日报”，false为“月报”
     */
    private void setTextTimeMMPatter(Boolean flag) {
        if (flag) {
            if (mm > 9) {
                home_text_time.setText(yy + "-" + mm + "-" + dd);
            } else {
                home_text_time.setText(yy + "-0" + mm + "-" + dd);
            }
        } else {
            if (mm > 9) {
                home_text_time.setText(yy + "-" + mm);
            } else {
                home_text_time.setText(yy + "-0" + mm);
            }
        }
    }
}
